package com.arron.algorithm.leetcodetop100.滑动窗口;

import java.util.HashMap;
import java.util.Map;

/**
 * 567. 字符串的排列
 *
 */
public class 字符串的排列 {



    public boolean checkInclusion(String s1, String s2) {


        if (s1.length()>s2.length()){
            return false;
        }

        //两个hashmap
        Map<Character,Integer> window = new HashMap<>();
        Map<Character,Integer> need = new HashMap<>();

        for (char c : s1.toCharArray()) {
            need.put(c,need.getOrDefault(c,0)+1);
        }

        int l = 0,r = 0;
        int valid = 0;
        while (r < s2.length()){

            char c = s2.charAt(r);
            r++;

            if (need.containsKey(c)){
                window.put(c,window.getOrDefault(c,0)+1);
                if (window.get(c).equals(need.get(c))){
                    valid++;
                }
            }

            if (r-l >=s1.length()){
                if (valid == need.size()){
                   return true;
                }

                //更新valid值
                if (need.containsKey(s2.charAt(l))){
                    if (window.get(s2.charAt(l)).equals(need.get(s2.charAt(l)))){
                        valid--;
                    }
                    window.put(s2.charAt(l),window.get(s2.charAt(l))-1);
                }

                //左指针移动
                l++;
            }
        }

        return false;
    }

}
